package com.guet.niit.Login.controller.user;

import com.guet.niit.Login.pojo.Account;
import com.guet.niit.Login.pojo.User;
import com.guet.niit.Login.service.UserService;
import com.guet.niit.User.pojo.ChargingRecord;
import com.guet.niit.User.pojo.UserCar;
import com.guet.niit.util.exitLogin;
import com.sun.javafx.stage.StageHelper;

import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class UserMenuFxController {
    @FXML
    Button carCharging;

    @FXML
    Button chargingRecord;

    @FXML
    Button topUpBalance;

    @FXML
    Button userInfo;

    @FXML
    Button updatePassword;

    @FXML
    Button exit;

    /**
     * 进入汽车充电版块
     * @param mouseEvent
     */
    public void enterCarCharging(MouseEvent mouseEvent) {
        //创建一个可选择的对话框
        List<String> choices = new ArrayList<>();
        choices.add("查询充电站");
        choices.add("结束充电");

        ChoiceDialog<String> dialog = new ChoiceDialog<>("查询充电站", choices);
        dialog.setTitle("选择");
        dialog.setHeaderText("选择您想使用的功能，点击ok后将进行下一步操作");
        dialog.setContentText("您的选择是:");

// 传统方式得到响应的值
        Optional<String> result = dialog.showAndWait();
        if (result.isPresent()){
            if (result.get().equals("查询充电站")){
                //引用fxml样式
                Parent load = null;
                try {
                    load = FXMLLoader.load(getClass().getResource("/fxml/user/selectChargingStations.fxml"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //获取当前窗口，并将Scene更换为用户菜单的Scene
                ObservableList<Stage> stageList = StageHelper.getStages();
                stageList.get(0).setScene(new Scene(load));

                //获取当前登录用户的id
                String name = Thread.currentThread().getName();
                long userId = Long.parseLong(name);
            }else {
                //获取当前登录用户的id
                String name = Thread.currentThread().getName();
                long userId = Long.parseLong(name);
                //调用service层查询用户汽车信息
                // 改进:(后面再改进为查询正在充电的汽车)
                com.guet.niit.User.service.UserService userService = new com.guet.niit.User.service.UserService();
                ArrayList<UserCar> userCars = userService.ReturnCarResult(userId);

                if (userCars.size()>0){
                    //引用fxml样式
                    Parent load = null;
                    try {
                        load = FXMLLoader.load(getClass().getResource("/fxml/user/chargingCarList.fxml"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //获取当前窗口，并将Scene更换为用户菜单的Scene
                    ObservableList<Stage> stageList = StageHelper.getStages();
                    stageList.get(0).setScene(new Scene(load));
                    //读取用户车辆信息
                    ChargingCarListFxController.chargingCarListFxController.readUserCarInfo(userCars);
                }else {
                    //引用fxml样式
                    Parent load = null;
                    try {
                        load = FXMLLoader.load(getClass().getResource("/fxml/user/nullChargingCarList.fxml"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //获取当前窗口，并将Scene更换为用户菜单的Scene
                    ObservableList<Stage> stageList = StageHelper.getStages();
                    stageList.get(0).setScene(new Scene(load));
                }
            }
//            System.out.println("Your choice: " + result.get());
        }

// 得到响应的值 (用lambda表达式)
//        result.ifPresent(letter -> System.out.println("Your choice: " + letter));
    }

    /**
     * 查看充电记录
     * @param mouseEvent
     */
    public void selectChargingRecord(MouseEvent mouseEvent) {
        //获取当前登录用户的id
        String name = Thread.currentThread().getName();
        long userId = Long.parseLong(name);
        //调用service层查询用户的充电记录
        com.guet.niit.User.service.UserService userService = new com.guet.niit.User.service.UserService();
        //1.查询充电记录表
        ArrayList<ChargingRecord> chargingRecords = userService.FindChargingRecordByUserId(userId);
        //2.查询用户汽车表
        ArrayList<UserCar> userCars = userService.ReturnCarResult(userId);
        //3.查询充电站表(可以考虑不要，因为charging_record表里没有相应的充电站id)

        //如果没有充电记录，则展示空界面
        if (chargingRecords.size()>0){
            //引用fxml样式
            Parent load = null;
            try {
                load = FXMLLoader.load(getClass().getResource("/fxml/user/chargingRecord.fxml"));

            } catch (IOException e) {
                e.printStackTrace();
            }
        //获取当前窗口，并将Scene更换为用户菜单的Scene
        ObservableList<Stage> stageList = StageHelper.getStages();
        stageList.get(0).setScene(new Scene(load));
        //读取个人充电记录
        ChargingRecordFxController.chargingRecordFxController.readChargingRecord(chargingRecords,userCars);

        }else {
            //引用fxml样式
            Parent load = null;
            try {
                load = FXMLLoader.load(getClass().getResource("/fxml/user/nullChargingRecord.fxml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        //获取当前窗口，并将Scene更换为用户菜单的Scene
        ObservableList<Stage> stageList = StageHelper.getStages();
        stageList.get(0).setScene(new Scene(load));
        }
    }

    /**
     * 充值余额
     * @param mouseEvent
     */
    public void topUpBalance(MouseEvent mouseEvent) {
        //获取当前登录用户的id
        String name = Thread.currentThread().getName();
        long userId = Long.parseLong(name);

        //调用service层查询用户的当前余额
        com.guet.niit.User.service.UserService userService = new com.guet.niit.User.service.UserService();
        Double balance = userService.ReturnBalace(userId);

        TextInputDialog dialog = new TextInputDialog("0.00");
        dialog.setTitle("余额充值");
        dialog.setHeaderText("您当前的余额为："+balance+"");
        dialog.setContentText("请输入您要充值的金额:");
        // 传统方式得到响应的值
        Optional<String> result =dialog.showAndWait();
        //用户点击确定
        if (result.isPresent()){
            //获取用户输入的金额
            String money = result.get();
            double inputMoney = Double.parseDouble(money);
            //用户输入的金额小于0则弹窗提示
            if (inputMoney<=0){
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText(null);
                alert.setContentText("输入的金额必须大于0!");
                alert.showAndWait();
            }else {
                //计算用户的余额数
                Double newBalance = balance+inputMoney;
                //调用service层修改用户的余额
                userService.UpdateBalanceByUserId(userId,newBalance);
            }
        }
// 得到响应的值 (用lambda表达式)
//        result.ifPresent(name -> System.out.println("Your name: " + name));
    }

    /**
     * 查看个人信息
     * @param mouseEvent
     */
    public void selectUserInfo(MouseEvent mouseEvent) {
        //引用fxml样式
        Parent load = null;
        try {
            load = FXMLLoader.load(getClass().getResource("/fxml/user/userInfo.fxml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取当前窗口，并将Scene更换为用户菜单的Scene
        ObservableList<Stage> stageList = StageHelper.getStages();
        stageList.get(0).setScene(new Scene(load));

        //获取当前登录用户的id
        String name = Thread.currentThread().getName();
        long userId = Long.parseLong(name);
        //根据用户id查询用户信息
        UserService userService = new UserService();
        //1、查询common_user表
        User users = userService.selectUserInfo(userId);
        //2、查询account表
        Account accounts = userService.selectAccount(userId);

        //读取个人信息
        //1、更新个人信息
        UserInfoFxController.userInfoFxController.readUserInfo(users);
        //2、更新个人账户
        UserInfoFxController.userInfoFxController.readUserAccount(accounts);

        //若用户的头像不为空，则将初始头像更换为用户自定义的头像
        if (users.getPhoto()!=null){

            //设置头像所在路径
            String newPhoto = "file:D:/img/"+users.getPhoto();
            //读取头像
            UserInfoFxController.userInfoFxController.readPhoto(newPhoto);
        }
    }

    /**
     * 修改个人密码
     * @param mouseEvent
     */
    public void updatePassword(MouseEvent mouseEvent) {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("修改前确认");
        dialog.setHeaderText("通过验证您输入的密码，确认是本人在操作后，才能修改密码!");
        dialog.setContentText("请输入您的原密码:");
        Optional<String> validateResult = dialog.showAndWait();

        //获取当前登录用户的id
        String name = Thread.currentThread().getName();
        long userId = Long.parseLong(name);

        //调用service层查询用户当前密码
        com.guet.niit.User.service.UserService userService = new com.guet.niit.User.service.UserService();
        String currentPassword = userService.returnPassword(userId);

        //用户点击确定后进行判断，如果密码符合，则进入密码修改界面
        if (validateResult.isPresent()){
            //获取用户输入的密码
            String inputPassword = validateResult.get();
            if (inputPassword.equals(currentPassword)){
                //引用fxml样式
                Parent load = null;
                try {
                    load = FXMLLoader.load(getClass().getResource("/fxml/user/updatePassword.fxml"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //获取当前窗口，并将Scene更换为用户菜单的Scene
                ObservableList<Stage> stageList = StageHelper.getStages();
                stageList.get(0).setScene(new Scene(load));

            }else {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText(null);
                alert.setContentText("您输入的密码有误!");
                alert.showAndWait();
            }
        }
    }

    /**
     * 退出
     * @param mouseEvent
     */
    public void exit(MouseEvent mouseEvent) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText(null);
        alert.setContentText("您确定要退出吗？");
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK){
//            Platform.exit();
            exitLogin.backtrack(UserMenuFxController.class);
        }else {
            alert.close();
        }
    }
}
